package base.thread;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

    static HashMap<String, String> map = new HashMap<>();

    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    static ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();


    public static String get(String key) {
        readLock.lock();
        try {
            System.out.println("read lock   starting.......");
            Thread.sleep(1000);
            return map.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            System.out.println("readLock   unlock***************  ");
            readLock.unlock();
        }

    }


    public static void set(String key, String value) {
        writeLock.lock();
        try {
            System.out.println("writeLock   lock   starting.......");
            Thread.sleep(1000);
            map.put(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("writeLock   unlock***************  ");
            writeLock.unlock();
        }
    }


    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();
        demo.set("key01", "value01");

        new Thread("thread01") {
            @Override
            public void run() {
                System.out.println("   " + demo.get("key01"));
            }
        }.start();

        new Thread("thread02") {
            @Override
            public void run() {
                System.out.println("   " + demo.get("key01"));
            }
        }.start();

        new Thread("thread03") {
            @Override
            public void run() {
                System.out.println("   " + demo.get("key01"));
            }
        }.start();


    }


}



















